Skip to content

Add 11 Animations for AnimationBehavior - #1232

Open
bijington wants to merge 125 commits into
mainfrom
feature/add-animations
Open

bijington wants to merge 125 commits into
mainfrom
feature/add-animations

Conversation

@bijington

@bijington bijington commented Jun 11, 2023 •

Copy link
Copy Markdown
Contributor

Description of Change

Adds 11 animations and reworks FadeAnimation, so AnimationBehavior ships 12 ready-made animations. Each one returns the view to its original values.

  • "To" animations (animate to a value, then back): FadeAnimation (reworked), ScaleAnimation, RotateAnimation, FlipHorizontalAnimation, FlipVerticalAnimation.
  • Attention seekers (keyframe animations): ShakeAnimation, TadaAnimation, HeartbeatAnimation, RubberBandAnimation, BounceAnimation, SwingAnimation, WobbleAnimation. They share one internal keyframe helper, so a view runs one seeker at a time.
  • Original values are tracked per view and property. A run started mid-run (for example a second tap) takes over from where the view is and still ends at the original value.
  • AnimationBehavior stops a running attention seeker before it starts, swallows the cancellation of its own AnimateCommand token, and stops and starts on the view's dispatcher in one UI turn.
  • Sample: AnimationBehaviorPage demos all 12 animations, plus a spin you can cancel with its token or with CancelAnimations().
  • Docs: Document the animations added in CommunityToolkit.Maui PR #1232 MicrosoftDocs/CommunityToolkit#674 adds a page per animation and documents the breaking changes below.
  • Naming conventions: adds a Naming Conventions section to CONTRIBUTING.md and to the agent instructions (AGENTS.md, .github/copilot-instructions.md, the code-style instructions and prompt), and the code this PR adds follows it.
CHANGED BEHAVIOUR (not breaking)
  • Animate is safe to call from any thread. Every animation moves to the view's dispatcher first, so it never writes the view from the thread pool.
  • AnimateCommand swallows the caller's own cancel. On main, a token cancelled before the command ran threw OperationCanceledException out of the async void command, which crashed the app unless SetShouldSuppressExceptionsInAnimations(true) was set. Other exceptions still reach the app.
  • AnimateCommand stops the running animations and starts the new one in one UI turn, from any thread. From a background thread, the interrupted run no longer returns the view to rest for a frame before the new run starts. AnimationType.Animate, including a custom animation's, now runs on the view's dispatcher.
  • An interrupted run with no successor returns the view to rest at once. After CancelAnimations(), or a second AnimationBehavior on the same view, the view is back at its original values and the Task completes. On main, an interrupted FadeAnimation faded back over another Length, or stayed partly faded when stopped on its way back.
  • Attention seekers stop running RotateToAsync, ScaleToAsync, ScaleXToAsync and ScaleYToAsync animations of the properties they animate (the toolkit's and the app's), and a toolkit "To" animation stops a running attention seeker that animates its property. An app's own ScaleToAsync, ScaleXToAsync, ScaleYToAsync or RotateToAsync that starts while Heartbeat, Tada, RubberBand, Swing or Wobble animates the same property takes over the same way: the seeker ends and returns its other properties to their original values. A direct write by the app does not stop a seeker.
  • A running TranslateToAsync keeps running and still reaches its target: Bounce, Shake and Wobble add their offset on top of the live translation, also when the translation starts while they run. The view ends at the translation's value, even when the translation writes exactly the value the seeker showed. A PropertyChanged handler that re-writes the translation during the seeker's write counts as part of that write.
  • A restore that throws (a throwing PropertyChanged handler) faults the animation's Task instead of escaping into MAUI's ticker, so SetShouldSuppressExceptionsInAnimations applies.
  • On Windows, a flip back to 0 removes the stale PlaneProjection that .NET MAUI leaves when another transform is set. A projection the app set itself stays, unless the flip turns the view: .NET MAUI replaces it then, and the flip clears MAUI's stale one.
  • System animations off (iOS Reduce Motion, Android "Remove animations"): every animation ends at the original values, also when animations are switched off mid-run.
  • RotateAnimation makes one full turn relative to the view's rotation: default Rotation 360, Length 400 ms. Xamarin Community Toolkit's RotateAnimation rotated to an absolute 180 degrees in 200 ms and snapped back to 0. FlipHorizontalAnimation and FlipVerticalAnimation still turn to an absolute angle.
Test coverage
  • Unit tests: the full suite passes (13,205 tests), also under tr-TR. That includes 579 tests in Animations (contract, timing, interruption, cancellation, system animations off, dispatch) and 750 in Behaviors, which also pass in Release.
  • Device tests: all 211 animation device tests pass on Android API 36, Android API 28, the iOS 27.0 simulator and Mac Catalyst, and all 217 on Windows packaged and unpackaged (0 failures, 0 skips). Each animation has its own device-test category (Category=FadeAnimation, Category=ScaleAnimation, ...).
  • Test harness: the single-thread unit tests run on an AsyncContext that is never disposed (UndisposedAsyncContext). AsyncContext.Run could crash the test host when AnimateCommand's async void ended on a pool thread while the context was being disposed, a race that also exists on main.
  • Slow CI timers: the mock ticker paces its 16 ms frames on a Stopwatch instead of Task.Delay(16), which slow CI runners stretch to 75-115 ms. Under macOS background priority, the Animations and Behaviors tests take about 2 minutes instead of 14, and no test uses more than a third of its timeout.
  • UI-thread stalls: a device test that acts in the middle of a run (cancel, trigger again, switch animations off, check the platform view) now acts in the same UI-thread turn that sees the run still going. It repeats an attempt, at most 5 times, only when a stalled UI thread let the whole run end first, and every attempt that acted keeps every assertion. With stalls injected on Mac Catalyst, the old tests failed 90 of 211; the new ones pass all 211 under three stall patterns and still catch 9 product mutations.
  • Mutation testing: removing the restore of the original values fails 31 device tests. Removing any guard of the interrupted-run logic, or splitting AnimateCommand's stop and start across UI turns, fails a unit test.
  • PR CI: the full device-test matrix passes on Android API 36 and 28, iOS 27 and 26.5, Mac Catalyst, and Windows packaged and unpackaged, plus the trimmed and NativeAOT jobs.

Linked Issues

PR Checklist

Additional information

  • Tested with unit tests (also under tr-TR), local device tests (Android API 36 and 28, iOS 27, Mac Catalyst, Windows), and the full device-test matrix in this PR's CI (Android, iOS, Mac Catalyst, Windows).
  • Also fixes an intermittent Windows failure in main's ExpanderTests.HeaderTapInAScrolledCollectionViewResizesTheContainerOfTheTappedItem (from Add Device Tests, Apply Fixes for Bugs Found #3344). The test looked up the item's Expander before WinUI had put it in the item's container; it now waits for it there. Test-only change.
  • Bounce, Shake and Wobble listen to VisualElement.BatchCommitted, which .NET MAUI raises after every animation tick, to keep their offset on top of a TranslateToAsync that started after them. The event is public but marked [EditorBrowsable(Never)]. Unit and device tests fail if a future .NET MAUI stops raising it on every tick.

Breaking changes

  • FadeAnimation.Length now covers the whole animation, fading out and back (Discussion FadeAnimation takes twice as long as expected #1231). Each half takes Length / 2. On main, both FadeToAsync calls used Length, so the default 300 ms fade took 600 ms.
  • Cancelling the token mid-run now returns the view to its original opacity, and a direct FadeAnimation.Animate call ends as canceled. On main, MAUI's FadeToAsync returned true on cancel and the fade back returned at once with the cancelled token, so the view stayed partly faded and the Task completed successfully. Through AnimateCommand, the view also returns, and the command still ends without an exception.
  • FadeAnimation.Opacity now defaults to BindingMode.OneWay (was TwoWay), and assigning NaN or an infinity is ignored. This matches the new animations' properties. A non-finite value would be written to the platform view on every frame.

🤖 Generated with Claude Code

@ghost ghost added stale The author has not responded in over 30 days help wanted This proposal has been approved and is ready to be implemented labels Aug 2, 2023
@VladislavAntonyuk

Copy link
Copy Markdown
Contributor

Will this PR resolve the animation doubled duration issue? #1231

@bijington

Copy link
Copy Markdown
Contributor Author

Yes it will

@bijington

Copy link
Copy Markdown
Contributor Author

I believe I have already addressed that issue in this PR I'm just struggling to get the unit test to prove it

@bijington

Copy link
Copy Markdown
Contributor Author

As far as I can tell it might be down to our use of Task.Delay in the mocking of the animation layer. I have been trying to investigate with a more accurate option for mocking

This comment was marked as outdated.

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
@TheCodeTraveler TheCodeTraveler self-assigned this Nov 12, 2026
TheCodeTraveler and others added 4 commits November 13, 2026 03:34
Co-Authored-By: Claude Code <noreply@anthropic.com>
Base Ticker.IsRunning reported on a Timer the mock never created, so every
Tweener.Start spawned an extra concurrent tick loop and animation timing ran
fast and uneven. The loop now tracks its own running state, Stop() clears it
before cancelling so a segment restarting inline from the finished callback
gets a fresh loop, and the loop captures its token so the dying loop cannot
be resurrected. Run the timing test on a single thread like FadeAnimationTests.

Co-Authored-By: Claude Code <noreply@anthropic.com>
…ir original values

- RotateAnimation, ScaleAnimation, ShakeAnimation, FlipHorizontalAnimation and FlipVerticalAnimation use
  [BindableProperty] partial properties and Defaults classes, like FadeAnimation on main.
- Each animation returns the view to the value it had before it started (Rotate and Shake used to snap to 0).
- AnimatedPropertyTracker generalizes FadeAnimation's per-view tracking to every animated property: an animation
  started while another one runs (e.g. AnimationBehavior triggered again) returns the view to its true original
  value; the interrupted animation stops where it is instead of fighting the new one.
- Animate throws ArgumentNullException synchronously and OperationCanceledException for a cancelled token.
- ShakeAnimation throws ArgumentOutOfRangeException for ReducingAmount <= 0, which used to hang the app.
- ShakeAnimation keeps the view's TranslationY instead of resetting it to 0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
FadeAnimation faded out over Length and back over Length again, so it took twice its Length
(#1231). It now spends half of Length on each direction,
like every other animation, and FadeAnimationTests inherits the BaseAnimationTests duration check.

Breaking change: FadeAnimation now plays twice as fast for the same Length.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
TheCodeTraveler and others added 5 commits November 19, 2026 21:10
…ntion seeker take over

An app's own .NET MAUI ScaleToAsync, ScaleXToAsync, ScaleYToAsync or RotateToAsync (and RelScaleToAsync, RelRotateToAsync)
that started while Heartbeat, Tada, RubberBand, Swing or Wobble animated the same property ticked after the seeker in
every frame, so it hid the seeker, and the seeker's restore then undid the app's target.

The later-started animation now takes over, as a toolkit ScaleAnimation or RotateAnimation already does: in its next
frame the seeker sees the app's animation handle running, ends, and its Task completes. The seeker leaves the taken-over
property to the app's animation and returns its other properties to their original values. A direct write by the app
still does not stop a seeker.

Unit tests cover every seeker and property pair, same-value, zero-length and cancelled animations, a To started inside
the seeker's start, and AnimationBehavior. One device theory runs five seeker and To pairs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ng a seeker takes over

Adds one sentence to the remarks of Heartbeat, Tada, RubberBand, Swing and Wobble: the seeker ends in its next frame, its
Task completes, its other properties return to rest, and the view keeps the value the app's animation reaches.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…e seeker writes

The takeover tests accepted any value between the app's start and target, so a seeker
that played its keyframes before checking for the takeover still passed (mutation: 9 of 24
rows green). They now require every write after the app's start to be one of the app's own
frame values, which makes that mutation fail 10 tests. Comments no longer claim the app's
animation always ticks after the seeker, as one started inside the seeker's start ticks before it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…s the seeker running

Tests only, no behavior change. An app's ScaleToAsync, ScaleXToAsync, ScaleYToAsync or RotateToAsync, and a toolkit RotateAnimation, that animate a property the running seeker does not animate must not end it. A change that ended every seeker whenever any of those animations ran passed all existing tests; the new rows (Heartbeat, Tada, RubberBand, Swing, Wobble, Bounce and Shake) fail under it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
TheCodeTraveler and others added 6 commits November 20, 2026 05:34
…e run still going

On a shared runner that stalls the UI thread, a whole run (or both 500 ms legs of a To
animation) can pass between the frame that met a test's mid-run wait and the moment the
test resumes. The test then waited out its timeout for a mid-run value that never came,
or cancelled, triggered, switched animations off or checked the platform view after the
run had already ended (Windows packaged, ab28da4: Scale and Heartbeat rows).

StartAndActMidRunAsync waits for a mid-run write or the run's end, then re-checks the
mid-run condition on the current value and runs the test's action synchronously in that
same UI-thread turn, so no frame can end the run in between. An attempt whose run ended
first proves nothing and is repeated with a fresh run, at most five times, with a clear
failure after that. Every attempt that acted keeps every assertion.

DisableSystemAnimations now switches in the caller's turn (MAUI's DispatchAsync always
posts), the Fade tests await their faded-opacity waits instead of racing the wait's
continuation, and waitTimeout is 30 s since it only bounds a hang.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The tests that start a seeker or a TranslateToAsync and act once it moves now act through
StartAndActMidRunAsync, with conditions that are false at rest and at the end of the run,
so a run that a stall let end is never taken for one in progress.

Seekers that only the test itself stops run for 60 s, so a stall cannot end them before
the test checks that they still run. The surviving-Swing test repeats an attempt only
when the Swing had its whole length before the test looked, and the two frame-sampling
Bounce tests only when no frame showed the hop and a gap between frames was long enough
to skip it. Every other attempt keeps every assertion.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
AnimationStartedMidRunAfterALateFrameReachesItsPeak sleeps a whole run length after the
start, which ends the first leg of every two-leg To animation at once. Rotate has one
leg, the whole run, so that frame ended the run itself: the old wait then acted on a run
that had already ended, and the new helper rightly never finds Rotate in progress. Rotate's
late frame now lands half way, which keeps a second run starting mid-run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
StartAndActMidRunAsync now checks run.IsCompleted before it acts, so a run
that already ended can never pass for one in progress. A run that ended
with its last value still mid-run is a product bug (the view was left
mid-animation), so the helper fails the test with the written values
instead of acting on the finished run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The cancel in AnimateCalledOffTheUIThreadChangesTheViewOnlyOnTheUIThread
and the trigger in AnimationBehaviorTriggeredOffTheUIThread... queue their
abort or start through the dispatcher. After a stall, a frame can run
ahead of an already queued item on some platforms (Android draws at the
vsync time), so with a 1-3 s run the run could end before the queued item
runs. A 10 s run leaves several seconds after the action. The behavior's
second run gets its normal length back inside the action, because the
running run read its length when it started.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… the translation

A stall before the first frame after the action is invisible to a
stopwatch started in the action, but MAUI hands the whole stall to the
bounce's first step. The two frame-sampling Bounce tests therefore read
the bounce's own ticker time: a linear sampler committed in the bounce's
turn gets the same milliseconds every frame. An attempt repeats only when
no frame's ticker time fell inside the span where the hop shows (computed
from Bounce's CubicOut/CubicIn keyframes) while the TranslateToAsync still
ran; every other attempt keeps every assertion.

BounceStartedWhileTranslateToRuns compares the hop with the translation's
own TranslationY in the same frame (derived from TranslationX, since one
linear tween moves both axes), so it holds wherever a stall lets the
translation get to before the first hop peaks.

RotateAnimationStopsASwing... no longer checks that Rotate is still
running after the Swing's posted end, which a stalled frame can jump; the
60 s Swing already proves that only Rotate ended it in time, and the test
now checks that the stopped Swing completes normally.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
TheCodeTraveler and others added 8 commits November 20, 2026 08:35
…issed run's fault

BounceDuringAHorizontalTranslateToHoldsTheFirstHopsPeakUntilItFalls,
TranslateToStartedDuringABounceKeepsTheHopsVisibleOnTopOfTheTranslation
and SwingWhoseStartAbortsARotateTo...KeepsTheTopEdgeAnchorUntilItEnds ran
their translate, restore and native-view checks only when a sampled frame
proved the scenario. A missed attempt dropped those checks although they
hold under any stall, so they now run after a missed attempt too.

AnimateCompletesAndReturnsTheViewToItsOriginalValues and
FlipFromZeroWithOtherTransformsSetReturnsThePlatformViewToRest check the
final values after a missed run. The helper awaits a missed run, so its
fault is not lost, and its mid-run failure message reports the run's
exception. The ticker-time comment no longer claims a platform-specific
stall behavior.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…-hardened device tests

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comment and assertion-message wording only. No code changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Renames two unit tests and a local that used animation jargon:
LeavesNoTweenTickingAfterItEnds becomes LeavesNoAnimationTickingAfterItEnds,
TokenCancelledWhileTheRunStartsItsTween_EndsCanceledWithoutPlayingTheTween
becomes TokenCancelledWhileTheRunStartsItsAnimation_EndsCanceledWithoutPlayingIt,
and isTweenRunning becomes isKeyframeAnimationRunning. No behavior change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
AnimateLegAsync is now AnimateAndRestoreIfStoppedAsync, the wrappers
and helpers are renamed to match, and "leg" in comments and test names
is plain words. No behavior change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Methods are verbs, past tense is only for events, success-bool methods
follow the Try-Parse pattern, and bools are questions. Added to
CONTRIBUTING.md, the Copilot and codestyle instructions, the codestyle
prompt, and a short Naming section in AGENTS.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Applies the approved rename plan to the code PR #1232 declares.

- Tracker: For, Start, End, ReturnedToOriginalValue and HandedOverToApp
  become GetOrCreate, StartAnimationAndGetOriginalValue, EndAnimation,
  RecordReturnToOriginalValue and RecordHandOverToApp.
- Bool methods follow the Try-Parse pattern: TryFindPropertiesTakenOverByTheApp
  (out list, null when false), TryAnimateAndRestoreIfStoppedAsync and the
  Try...Async wrappers in the Fade, Scale and Flip animations.
- Keyframe builders become Create<Motion>Keyframe, KeyframeTarget getters
  start with Get, and the keyframe Start becomes StartRun.
- Tasks end in Task, TaskCompletionSources in Source, the one
  ManualResetEventSlim in Signal; bool locals read as questions.
- Test helpers, parameters and test-name prefixes follow the same rules.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Add the On<EventName> handler and callback rule and the Task and
TaskCompletionSource suffix rule to the Naming Conventions sections
and the short version in AGENTS.md.

Fix older guide content that contradicted the rules: fold the old Try
Pattern section into the Try-Parse rule, rename the Success tuple
element to WasParsed, readyToPlay to readyToPlaySource and _tcs to
orderSource, drop the range-indexer and nullability-attribute comments
that said what, point the stale best practices bullet at the naming
section, and say "number" instead of "tense" for enums.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@TheCodeTraveler

Copy link
Copy Markdown
Collaborator

Hi Shaun (@bijington)! This is Brandon's Claude.

Thank you for requesting the last Copilot review! Its 3 comments are fixed, replied to and resolved, and CI is green. Could you request one more Copilot review when you get a chance?

The fixes:

  • A flip on Windows that never turns the view now keeps a PlaneProjection the app set.
  • Bounce, Shake and Wobble keep their offset on top of a TranslateToAsync that starts while they run, and restore the right translation afterwards.

Also new since then:

  • An app's own ScaleToAsync or RotateToAsync that starts during Heartbeat, Tada, RubberBand, Swing or Wobble now takes over, as ScaleAnimation and RotateAnimation already did.
  • The animation device tests no longer flake when a CI runner stalls the UI thread.
  • CONTRIBUTING.md and the agent instructions now have a Naming Conventions section, and this PR's code follows it.
  • [Proposal] One shared, tested animation library for every toolkit animation #3449 proposes moving every toolkit animation, including TouchBehavior's, onto these tested guards, as a follow-up to this PR.

TheCodeTraveler and others added 3 commits November 20, 2026 13:57
…red animator scale helper

#3433 added API 25 to the device-test matrix and AnimatorDurationScale, which switches the
animator scale on below API 26. Use it as TouchBehaviorTestBase does instead of skipping.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@TheCodeTraveler

Copy link
Copy Markdown
Collaborator

Hi Shaun (@bijington)! This is Brandon's Claude.

Thank you again for requesting the Copilot reviews! I updated this PR from main and fixed the merge conflict. Could you request another Copilot review when you get a chance?

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

return;
}

if (GetTransformedView(view) is FrameworkElement platformView && platformView.Projection is PlaneProjection projection && !ReferenceEquals(projection, projectionAtStart))
{ 0.6, 1.0, CreateBeatKeyframe(beatScale, originalScale) },
};

Animation CreateBeatKeyframe(double fromScale, double toScale) => new(scale => view.Scale = scale, fromScale, toScale, Easing.SinInOut);

public void Stop() => view.BatchCommitted -= HandleBatchCommitted;

public double GetValueToRestore() => WasWrittenByAnotherWriter() ? (double)view.GetValue(property) : baseValue;
{
{ 0.0, 0.1, CreateScaleKeyframe(originalScale, shrunkScale) },
{ 0.2, 0.3, CreateScaleKeyframe(shrunkScale, grownScale) },
{ 0.9, 1.0, CreateScaleKeyframe(grownScale, originalScale) },
};

Animation CreateScaleKeyframe(double fromScale, double toScale) => new(scale => view.Scale = scale, fromScale, toScale, Easing.SinInOut);
Animation CreateTiltKeyframe(double fromOffset, double toOffset) => new(rotation => view.Rotation = rotation, originalRotation + fromOffset, originalRotation + toOffset, Easing.SinInOut);

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

breaking change This label is used for PRs that include a breaking change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants